#include <gl/glew.h>
#include <gl/glut.h>
#include <stdlib.h>

static int leftFirst = GL_TRUE;

static void Init()
{
  glewInit();

  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);  // srcColor * alpha + dst * (1-alpha)
  glShadeModel(GL_FLAT);
  glClearColor(0, 0, 0, 0);
}

static void DrawLeftTriangle()
{
  glBegin(GL_TRIANGLES);
  glColor4f(1.0f, 0.0f, 0.0f, 0.5f); // alpha = 0.75
  glVertex3f(0.1, 0.9, 0.0);
  glVertex3f(0.1, 0.1, 0.0);
  glVertex3f(0.7, 0.5, 0.0);
  glEnd();
}

static void DrawRightTriangle()
{
  glBegin(GL_TRIANGLES);
  glColor4f(0.0f, 0.0f, 1.0f, 0.5f); // alpha = 0.75
  glVertex3f(0.9, 0.9, 0.0);
  glVertex3f(0.3, 0.5, 0.0);
  glVertex3f(0.9, 0.1, 0.0);
  glEnd();
}

void Display()
{
  glClear(GL_COLOR_BUFFER_BIT);

  if(leftFirst)
  {
    DrawLeftTriangle();
    DrawRightTriangle();
  }else{
    DrawRightTriangle();
    DrawLeftTriangle();
  }

  glFlush();
}

void Reshape(int w, int h)
{
  glViewport(0,0, (GLsizei)w, (GLsizei)h);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();

  if(w<=h)
    gluOrtho2D(0.0, 1.0, 0.0, 1.0*(GLfloat)h/(GLfloat)w);
  else
    gluOrtho2D(0.0, 1.0*(GLfloat)h/(GLfloat)w, 0.0, 1.0);
}

void Keyboard(unsigned char key, int x, int y)
{
  switch(key)
  {
  case 't':
  case 'T':
    leftFirst = !leftFirst;
    glutPostRedisplay();
    break;
  case 27:
    exit(0);
    break;
  default:
    break;
  }
}

int main(int argc, char* argv[])
{
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
  glutInitWindowSize(200, 200);
  glutCreateWindow(argv[0]);
  Init();

  glutReshapeFunc(Reshape);
  glutKeyboardFunc(Keyboard);
  glutDisplayFunc(Display);
  glutMainLoop();

  return 0;
}